package com.workstudy.web.controller.workstudy;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.workstudy.common.core.domain.entity.SysRole;
import com.workstudy.common.core.domain.entity.SysUser;
import com.workstudy.common.utils.ShiroUtils;
import com.workstudy.system.service.ISysUserService;
import com.workstudy.workstudy.domain.WorkstudyAttendanceVo;
import com.workstudy.workstudy.domain.WorkstudyAttendanceset;
import com.workstudy.workstudy.domain.WorkstudyPost;
import com.workstudy.workstudy.service.IWorkstudyAttendancesetService;
import com.workstudy.workstudy.service.IWorkstudyPostService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.workstudy.common.annotation.Log;
import com.workstudy.common.enums.BusinessType;
import com.workstudy.workstudy.domain.WorkstudyAttendance;
import com.workstudy.workstudy.service.IWorkstudyAttendanceService;
import com.workstudy.common.core.controller.BaseController;
import com.workstudy.common.core.domain.AjaxResult;
import com.workstudy.common.utils.poi.ExcelUtil;
import com.workstudy.common.core.page.TableDataInfo;

/**
 * 考勤Controller
 * 
 * @author ws
 * @date 2021-03-28
 */
@Controller
@RequestMapping("/workstudy/attendance")
public class WorkstudyAttendanceController extends BaseController
{
    private String prefix = "workstudy/attendance";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWorkstudyPostService workstudyPostService;

    @Autowired
    private IWorkstudyAttendanceService workstudyAttendanceService;

    @Autowired
    private IWorkstudyAttendancesetService workstudyAttendancesetService;

    @RequiresPermissions("workstudy:attendance:view")
    @GetMapping()
    public String attendance()
    {
        return prefix + "/attendance";
    }

    /**
     * 查询考勤列表
     */
    @RequiresPermissions("workstudy:attendance:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkstudyAttendance workstudyAttendance)
    {
        //获取登录的用户role
        List<SysRole> roleList = ShiroUtils.getSysUser().getRoles();
        for(SysRole role:roleList){
            //如果是学生就查出他自己的
            if("student".equals(role.getRoleKey())){
                workstudyAttendance.setUserId(ShiroUtils.getUserId());
            }
        }
        startPage();
        List<WorkstudyAttendance> list = workstudyAttendanceService.selectWorkstudyAttendanceList(workstudyAttendance);
        return getDataTable(list);
    }

    /**
     * 导出考勤列表
     */
    @RequiresPermissions("workstudy:attendance:export")
    @Log(title = "考勤", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WorkstudyAttendance workstudyAttendance)
    {
        List<WorkstudyAttendance> list = workstudyAttendanceService.selectWorkstudyAttendanceList(workstudyAttendance);
        ExcelUtil<WorkstudyAttendance> util = new ExcelUtil<WorkstudyAttendance>(WorkstudyAttendance.class);
        return util.exportExcel(list, "attendance");
    }

    /**
     * 新增考勤
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {

        //查询岗位
        WorkstudyPost workstudyPost=new WorkstudyPost();
        workstudyPost.setStatus("1");
        workstudyPost.setAnnouncerBy(ShiroUtils.getLoginName());
        List<WorkstudyPost> postList = workstudyPostService.selectWorkstudyPostList(workstudyPost);
        mmap.put("postList", postList);
        //查询学生
        List<SysUser> userList = userService.selectUserByroleKeys("student");
        mmap.put("students", userList);
        return prefix + "/add";
    }

    /**
     * 新增保存考勤
     */
    @RequiresPermissions("workstudy:attendance:add")
    @Log(title = "考勤", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WorkstudyAttendance workstudyAttendance)
    {
        //获取考勤设置
        WorkstudyAttendanceset workstudyAttendanceset = workstudyAttendancesetService.selectWorkstudyAttendancesetById(1L);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = formatter.format(workstudyAttendance.getStartTime());
        String endTime = formatter.format(workstudyAttendance.getEndTime());
        //获取工作时长
        double hour = calculatetimeGapHour(startTime, endTime);
        BigDecimal decimal = new BigDecimal(hour);

        //设置工作时长
        workstudyAttendance.setDuration(decimal);

        //判断当天工作时长是否大于考勤设置的每天最大工作时长
        int i = workstudyAttendance.getDuration().compareTo(new BigDecimal(workstudyAttendanceset.getMaxtime()));
        if(1==i){
            return error("当天工作时长不能大于考勤设置的每天"+workstudyAttendanceset.getMaxtime()+"小时工作时长!");
        }
        int count = workstudyAttendanceService.selectWorkstudyAttendanceByCount(workstudyAttendance);
        if(count>workstudyAttendanceset.getMaxday().intValue()){
            return error("不能大于考勤设置的每周"+workstudyAttendanceset.getMaxday()+"次工作次数!");
        }
        return toAjax(workstudyAttendanceService.insertWorkstudyAttendance(workstudyAttendance));
    }

    /**
     * 修改考勤
     */
    @GetMapping("/edit/{attendanceId}")
    public String edit(@PathVariable("attendanceId") Long attendanceId, ModelMap mmap)
    {
        //查询岗位
        WorkstudyPost workstudyPost=new WorkstudyPost();
        workstudyPost.setStatus("1");
        List<WorkstudyPost> postList = workstudyPostService.selectWorkstudyPostList(workstudyPost);
        mmap.put("postList", postList);
        //查询学生
        List<SysUser> userList = userService.selectUserByroleKeys("student");
        mmap.put("students", userList);
        WorkstudyAttendance workstudyAttendance = workstudyAttendanceService.selectWorkstudyAttendanceById(attendanceId);
        mmap.put("workstudyAttendance", workstudyAttendance);
        return prefix + "/edit";
    }

    /**
     * 修改保存考勤
     */
    @RequiresPermissions("workstudy:attendance:edit")
    @Log(title = "考勤", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WorkstudyAttendance workstudyAttendance)
    {
        return toAjax(workstudyAttendanceService.updateWorkstudyAttendance(workstudyAttendance));
    }

    /**
     * 删除考勤
     */
    @RequiresPermissions("workstudy:attendance:remove")
    @Log(title = "考勤", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(workstudyAttendanceService.deleteWorkstudyAttendanceByIds(ids));
    }

    /**
     * 查询考勤列表
     */
    @GetMapping("/getAttendanceUserIdlist")
    @ResponseBody
    public List<WorkstudyAttendance>  getAttendanceUserIdlist(Long userId)
    {
        WorkstudyAttendanceVo workstudyAttendance=new WorkstudyAttendanceVo();
        workstudyAttendance.setStatus("0");
        workstudyAttendance.setUserId(userId);
        List<WorkstudyPost> workstudyPostList = workstudyPostService.selectWorkstudyPostByAnnouncerBy(ShiroUtils.getLoginName());
        String postids="";
        for (WorkstudyPost w : workstudyPostList) {
            postids += "'" + w.getPostId() + "',";
        }
        workstudyAttendance.setPostIds(postids.substring(0,postids.length()-1));
        List<WorkstudyAttendance> list = workstudyAttendanceService.selectWorkstudyAttendanceList2(workstudyAttendance);
        return list;
    }

    /** 比较两个时间相差小时 */
    public static double calculatetimeGapHour(String time1, String time2) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        double hour = 0;
        try {
            Date date1, date2;
            date1 = simpleDateFormat.parse(time1);
            date2 = simpleDateFormat.parse(time2);
            double millisecond = date2.getTime() - date1.getTime();
            hour = millisecond / (60 * 60 * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return hour;
    }
}
